$(document).ready(function(){
	$('.pf').inputmask({"mask":"0.99", "greedy": false });
	$('.multiplier').change(function(){
		if($(this).val()==0){
			$(this).val();
			$.notify('Multiplier can not be zero or blank','error');
		}
	});
	$('.numeric, .multiplier').keyup(function(){
		var _val=$(this).val();
		var _length=_val.length;
		var ln=_length-1;
		if(isNaN($(this).val())){
			$(this).val(_val.slice(0,ln));
		}
	});
	$('form').find('input, select, textarea ').each(function (){
		if($(this).hasClass('required')){
			$(this).parent().append("<span style='color:red; padding:5px'>*Required</span>");
		}
	});
});

//checks if visible
function isVisible(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

//For the motor creation page
$(document).ready(function(){
	$('#installationDetails').hide();
	$('#step3').hide();
	$('#step1').show();
	$('#step2').hide();
	$('#isInstalled').click(function(){
		$('#installationDetails').toggle();
		if($('#installationDetails').css('display')=='block'){
			$('#installationDetails input').each(function (){
				if($(this).attr('id')!="lstMaintain"){
					$(this).addClass('required');
					$(this).removeClass('optional');
					if($(this).parent().find('span').length==0) {
						$(this).parent().append("<span style='color:red; padding:5px'>*Required</span>");
					}
				}
			});
		}else{
			$('#installationDetails input').each(function (){
				$(this).removeClass('required');
				$(this).addClass('optional');
			});
		}
			
	});
	
	
	$('#n').attr('checked', 'checked');
	$('.custom').hide();
	$('input:radio').click(function(){
	if($('#y').is(':checked')) {
			$('.custom').find('input[for]').each(function(i,v){
				$(this).addClass('required');
			});
			$('.custom').show();
	}
	else{
		$('.custom').find('.required').each(function(i,v){
			$(this).removeClass('required');
		});
		$('.custom').hide();
	}
	$("#showimg").html("");		
	});
	$('#1stcreate').click(function(){
		if(validateForm("#newasset")){
			$('#step1').hide();
			$('#step2').show();
		}
	});
	$('#2ndcreate').click(function(){
		var additionalFields=$('#newasset #y').is(':checked');
		if(additionalFields){
			if(!validateForm("#newasset")) return false;
			appendToKPIList();
			$('#step2').hide();
			$('#step3').show();
		}
		else{
			$('#newasset').submit();
		}
		
	});
	$('#backto1ststep').click(function(){
		if(!validateForm("#newasset")) return false;
		$('#step2').hide();
		$('#step1').show();
	});
	$('#backto2ststep').click(function(){
		$('#step2').show();
		$('#step3').hide();
		$('.1stfield option[for="additionalfield"]').each(function(){
			$(this).remove();
		});
		$('.2ndfield option[for="additionalfield"]').each(function(){
			$(this).remove();
		});
	});
	
});
	function appendToKPIList(){
		$('#additionalFieldBlock input').each(function(){
			if($(this).attr('class')=='newFields required'){
				var v=$(this).val();
				v=$.trim(v);
				var k=v.split(" ").join("_");
				if($('.1stfield').find('option[value="'+k+'"]').length==0){
					if(!v || v=="") return;
					$('.1stfield').append('<option for="additionalfield" value="'+k+'">'+v+'</option>');
				}
			
				if($('.2ndfield').find('option[value="'+k+'"]').length==0){
					if(!v || v=="") return;
					$('.2ndfield').append('<option for="additionalfield" value="'+k+'">'+v+'</option>');
				}
				
			}
		});

	}
	
	function addKPI(t,v){
		var optionList=$(t).parent().parent().parent().find('select#1stfield.1stfield option');
		var finalArray=new Array();
		optionList.each(function(){
			var key=$(this).val();
			var display=$(this).html();
			finalArray.push({key:key,display:display});
		});
		var jsonString = JSON.stringify(finalArray);
		$.ajax({
			type:"POST",
			url:"ajax.php?action=addKPI&val="+v,
			data: {data: jsonString},
			success:function(res){
				$('#custom_field_div').append(res);
			}
		});
		$(t).replaceWith("<img width='10px' hight='15px' src='images/minus.ico' onclick='removeKPI(this)' />");
	}	
	function removeKPI(t){
		$(t).parent().parent().parent().remove();
	}
	function addKPI_O(v){
		$.ajax({
			type:"POST",
			url:"ajax.php?action=addKPI&val="+v,
			success:function(data){
				$('#custom_field_div').append(data);
				//alert("Done appending ...");
				setTimeout(function() {appendToKPIList()},10);
			}
		});
	}
	
	// function to show notification
	function showNotification(title,message) {
	var id = $.gritter.add({
				title: title,
				text: message,
			});
	return id;
}


// Define the goTo function

(function($) {
    $.fn.goTo = function() {
        $('html, body').animate({
            scrollTop: ($(this).offset().top-100) + 'px'
        }, 'fast');
        return this; // for chaining...
    }
})(jQuery);

function highlightFieldForError(r,name) {
	
	if(r==null) {
		r = '';
	} else {
		r= r+"_";
	}

	// Make the element visible
	if(!isVisible("#"+r+name)) {
		$("#"+r+name).goTo();
	}
	
	// Focus the element
	$("#"+r+name).focus();
	
	// Highlight with colour
	$("#"+r+name).animate({backgroundColor:'#FFFF88'},0000,function(){
		$("#"+r+name).animate({backgroundColor:'white'},4000,function(){});
	});
}

function clearFieldValue(r,name) {
	
	if(r==null) {
		r = '';
	} else {
		r= r+"_";
	}
	
	// Clear the value
	$("#"+r+name).val("");

}

function checkPassword(_this,password){
	if($(_this).val()!="" && $(_this).val()!=password){
		$.notify("password did not match","error");
		$(_this).val("");
		$(_this).focus();
		return false;
	}
}

//unique email id check
	$(document).ready(function(){
		var latestVal="";
		$('#adduserForm #email').keyup(function(){
			$('#adduserForm input[type=submit]').attr('disabled','disabled');
			latestVal=$(this).val();
		});
		$('#adduserForm #email').change(function(){
			_this=$(this);
			var emailId=$(this).val();
			$.ajax({
				url:"ajax.php?action=checkForUniqueEmail&emailId="+emailId,
				beforeSent:$(_this).parent().find('span').html('Checking Tag'),
				success:function(res){
					var goodToGo=res.trim();
					if(goodToGo=='1' && latestVal==emailId){
						$(_this).parent().find('span').html("<img style='padding:5px' height='18px' width='18px' src='images/tick.ico' /> </span>");
						$('#adduserForm input[type=submit]').removeAttr('disabled');
					}else{
						$.notify('This email id already exists','error');
						$(_this).parent().find('span').html("<img style='padding:5px' height='18px' width='18px' src='images/cross.ico' /> </span>");
						$('#adduserForm input[type=submit]').attr('disabled','disabled');
					}
				}
			});
		
		});
		
	});

function passwordResetEmail(id){
	$.ajax({
		beforeSent:$("#sendPassLink").val("sending.."),
		url:"ajax.php?action=passwordResetEmail&id="+id,
		success:function(res){
			var response=JSON.parse(res);
			$.notify(response['msg'],response['status']);
			$("#sendPassLink").val("send email");
		}
	});
}

//from reset password form of email link
function changePassword(uId){
	var p=$.trim($("#password").val());
	var cp=$.trim($("#passwordRecheck").val());
	if(p!="" && cp!="" && p==cp){
		$.ajax({
			beforeSent:$("#sendPassLink").val("sending.."),
			url:"ajax.php?action=changePassword&uId="+uId+"&psw="+p,
			success:function(res){
				var response=JSON.parse(res);
				$("#content").html(response['msg']);
			}
		});
	
	}else{
		$.notify("Enter password and confirm password correctly", "error")
	}
}

